<template>
  <div
    v-loading="loading"
    class="rc-cont relative-amount-ratio">
    <div
      v-for="(item, index) in list"
      :key="index"
      class="amount-ratio-table-item">
      <div class="amount-ratio-table-header">
        <div
          v-if="['business', 'receivables', 'contract'].includes(crmType)"
          style="font-size: 16px;">
          {{ crmType | keyToNameData }}金额（{{ unit }}）：{{ formatMoney(item.money) }}
        </div>

        <div
          v-if="crmType == 'customer'"
          style="font-size: 16px;">
          <span>{{ item.label | typeToNameData }}{{ item.label == 5 ? '名称' : '编号' }}：</span>
          <span
            class="can-visit--underline"
            @click="handleClick('checkDetail', index)">{{ item.name }}</span>
          <span style="margin-left: 20px;">{{ item.label | typeToNameData }}金额（{{ unit }}）：{{ item.money }}</span>
        </div>

        <div style="flex: 1; text-align: right;">
          <el-button
            v-if="!item.list.length && amountRatioAuth(item.label)"
            icon="el-icon-plus"
            @click="handleClick('create')">金额比例设置</el-button>
          <el-button
            v-if="item.list.length && amountRatioAuth(item.label)"
            @click="handleClick('edit', index)">编辑</el-button>
          <el-button
            v-if="item.list.length && amountRatioAuth(item.label)"
            @click="handleClick('delete', index)">删除</el-button>
        </div>
      </div>

      <el-table
        :data="item.list"
        :max-height="tableHeight"
        stripe
      >
        <el-table-column
          v-for="(sItem, sIndex) in fieldList"
          :key="sIndex"
          :prop="sItem.prop"
          :label="sItem.label"
          :min-width="sItem.width"
          :formatter="fieldFormatter"
          show-overflow-tooltip
        />
      </el-table>
    </div>

    <el-dialog
      :title="createOrEditTitle"
      :visible.sync="createOrEditShow"
      append-to-body
      custom-class="amount-ratio-dialog"
      :close-on-click-modal="false"
      width="900px">
      <el-button
        type="primary"
        @click="membersDepVisible = true">选择分配对象</el-button>
      <el-table
        :data="createTableList"
        :max-height="300"
        stripe>
        <el-table-column
          v-for="(item, index) in fieldList.filter(o => o.prop != 'money')"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          :formatter="createFieldFormatter"
          align="center"
          show-overflow-tooltip>
          <template slot-scope="{ row, column }">
            <span v-if="column.property == 'allocation'">
              {{ createFieldFormatter(row, column) }}
            </span>
            <el-input-number
              v-else
              v-model="row[column.property]"
              style="width: 100px;"
              :min="0"
              :max="column.property == 'ratio' ? 100 : Infinity"
              :controls="false"
              :precision="2"
            />
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          align="center"
          label="操作">
          <template slot-scope="{ $index }">
            <i
              style="cursor: pointer;"
              class="wk wk-delete"
              @click="handleClick('remove', $index)" />
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="createOrEditShow = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <wk-dep-user-dialog
      :user-value.sync="users"
      :dep-value.sync="strucs"
      :visible.sync="membersDepVisible"
      :sub-dept-contain.sync="isNeedChild"
      :props="{
        showSubDeptContain: true,
        showDisableUser: false
      }"
      @click.native.stop
      @close="membersDepCancel"
      @change="membersDepSelect"
    />

    <c-r-m-all-detail
      :id="relatedID"
      :visible.sync="showRelatedDetail"
      :crm-type="relatedCRMType"
      :no-listener-class="['el-table__body']"
      @handle="getList" />

    <div
      v-if="nopermission"
      v-empty="nopermission"
      class="empty"
      xs-empty-text="暂无数据" />
  </div>
</template>

<script type="text/javascript">
import {
  crmGetRatioSettingAPI,
  saveOrUpdateRatioSettingAPI,
  deleteRatioSettingAPI
} from '@/api/crm/common'

import CheckStatusMixin from '@/mixins/CheckStatusMixin'
import crmTypeModel from '@/views/crm/model/crmTypeModel'
import NP from 'number-precision'
import { mapGetters } from 'vuex'

export default {
  name: 'RelativeAmountRatio', // 金额比例设置
  components: {
    WkDepUserDialog: () => import('@/components/NewCom/WkUserDialogSelect/Dialog'),
    CRMAllDetail: () => import('@/views/crm/components/CRMAllDetail')
  },

  filters: {
    // 根据key获取name
    keyToNameData(key) {
      return crmTypeModel.keyToNameData[key]
    },

    // 根据type获取name
    typeToNameData(type) {
      return crmTypeModel.typeToNameData[type]
    }
  },
  mixins: [CheckStatusMixin],
  inject: ['rootTabs'],
  props: {
    /** 模块ID */
    id: [String, Number],
    /** 没有值就是全部类型 有值就是当个类型 */
    crmType: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      loading: false,
      list: [],
      nopermission: false,

      tableHeight: '250px',

      createOrEditShow: false, // 新建/编辑
      createOrEditTitle: '', // 新建/编辑标题
      createTableList: [],

      // 选择员工
      membersDepVisible: false,
      users: [], // 员工
      strucs: [], // 部门
      isNeedChild: 0,

      type: 'save',
      editData: {},

      // 相关
      relatedID: '',
      showRelatedDetail: false,
      relatedCRMType: ''
    }
  },

  computed: {
    ...mapGetters(['crm']),
    // 字段列表
    fieldList() {
      return [
        {
          label: '分配对象',
          prop: 'allocation'
        },
        {
          label: '提成比例(%)',
          prop: 'ratio'
        },
        {
          label: '系数',
          prop: 'coefficient'
        },
        {
          label: `提成金额(${this.unit})`,
          prop: 'money'
        }
      ]
    },

    // 单位转换
    unit() {
      return this.$unit('crm')
    },

    // 金额比例操作权限
    amountRatioAuth() {
      return (label) => {
        const authObj = {
          5: this.businessAmountRatioAuth,
          6: this.contractAmountRatioAuth,
          7: this.receivablesAmountRatioAuth
        }

        return authObj[label]
      }
    },

    // 商机金额比例操作权限
    businessAmountRatioAuth() {
      return this.crm.business && this.crm.business.saveOrUpdateRatioSetting
    },

    // 合同金额比例操作权限
    contractAmountRatioAuth() {
      return this.crm.contract && this.crm.contract.saveOrUpdateRatioSetting
    },

    // 回款金额比例操作权限
    receivablesAmountRatioAuth() {
      return this.crm.receivables && this.crm.receivables.saveOrUpdateRatioSetting
    }
  },

  watch: {
    id(val) {
      this.getList()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeAmountRatio') {
        this.getList()
      }
    }
  },

  mounted() {
    this.getList()
  },

  methods: {
    /**
     * @description: 获取展示数据
     * @return {*}
     */
    getList() {
      this.loading = true
      crmGetRatioSettingAPI({
        label: crmTypeModel.keyToTypeData[this.crmType],
        typeId: this.id
      })
        .then(res => {
          const data = res.data || []
          if (!data.length) {
            this.nopermission = true
          }
          this.list = data
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 按钮点击操作
     * @param {*} type
     * @param {*} index
     * @return {*}
     */
    handleClick(type, index) {
      if (type == 'create') {
        this.createOrEditTitle = '新建金额比例设置'
        this.createTableList = []
        this.type = 'save'
        this.createOrEditShow = true
      } else if (type == 'edit') {
        this.createOrEditTitle = '编辑金额比例设置'
        this.type = 'update'
        this.editData = this.list[index]
        const list = this.list[index].list || []
        this.createTableList = list.map(item => {
          return {
            allocationName: item.allocationName,
            allocationId: item.allocationId,
            ratio: item.rate,
            coefficient: item.coefficient,
            isNeedChild: item.isNeedChild,
            allocationType: item.allocationType
          }
        })
        this.createOrEditShow = true
      } else if (type == 'checkDetail') { // 查看详情
        const { label, typeId } = this.list[index]
        this.relatedCRMType = crmTypeModel.typeToKeyData[label]
        this.relatedID = typeId
        this.showRelatedDetail = true
      } else if (type == 'delete') { // 列表删除
        this.$confirm('确定删除金额比例设置吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const { typeId } = this.list[index]
          deleteRatioSettingAPI(typeId)
            .then(() => {
              this.loading = false
              this.$message.success('删除成功')
              this.getList()
            })
            .catch(() => {
              this.loading = false
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else if (type == 'remove') { // 新建编辑删除
        this.createTableList.splice(index, 1)
      }
    },

    /**
     * @description: 员工、部门选择确定
     * @param {*} userIds
     * @param {*} deptIds
     * @param {*} users
     * @param {*} strucs
     * @return {*}
     */
    membersDepSelect(userIds, deptIds, users, strucs) {
      if (!users.length && !strucs.length) {
        this.users = []
        this.strucs = []
      } else {
        const selectUsers = users.map(item => { return { allocationId: item.userId, allocationName: item.realname } })
        const selectStrucs = strucs.map(item => { return { allocationName: item.name, allocationId: item.deptId } })
        const selectIds = this.createTableList.map(o => o.allocationId)
        if (selectUsers.some(o => selectIds.includes(o.allocationId)) || selectStrucs.some(o => selectIds.includes(o.allocationId))) {
          this.$message.error('已存在相同的分配对象')
          return
        }

        selectUsers.forEach(item => {
          this.createTableList.push({
            ...item,
            ratio: 0,
            coefficient: 0,
            allocationType: 0
          })
        })
        selectStrucs.forEach(item => {
          this.createTableList.push({
            ...item,
            ratio: 0,
            coefficient: 0,
            allocationType: 1,
            isNeedChild: this.isNeedChild
          })
        })
      }
    },

    /**
     * @description: 员工、部门选择取消
     * @return {*}
     */
    membersDepCancel() {
      this.users = []
      this.strucs = []
    },

    /**
     * @description: 金额转换
     * @param {*} money
     * @return {*}
     */
    formatMoney(money) {
      return this.$money('crm', money)
    },

    /**
     * @description: 新建/编辑保存
     * @return {*}
     */
    save() {
      if (!this.createTableList.length) {
        this.$message.error('请添加分配对象')
        return
      }

      // let ratio = 0
      // this.createTableList.forEach(item => {
      //   ratio = NP.plus(ratio, Number(item.ratio))
      // })

      // if (ratio != 100) {
      //   this.$message.error('提成比例之和必须为100%')
      //   return
      // }

      const params = {
        label: crmTypeModel.keyToTypeData[this.crmType],
        data: {
          allocationList: this.createTableList,
          label: this.type == 'save' ? crmTypeModel.keyToTypeData[this.crmType] : this.editData.label,
          operationType: this.type == 'save' ? 1 : 2,
          typeId: this.type == 'save' ? this.id : this.editData.typeId
        }
      }

      saveOrUpdateRatioSettingAPI(params)
        .then(() => {
          this.$message.success('保存成功')
          this.createOrEditShow = false
          this.createTableList = []
          this.getList()
        })
    },

    /**
     * @description: 格式化字段
     * @param {*} row
     * @param {*} column
     * @return {*}
     */
    fieldFormatter(row, column) {
      // 如果需要格式化
      if (column.property == 'allocation') {
        if (row.allocationType == 0) { // 员工
          return row.allocationName
        } else if (row.allocationType == 1) { // 部门
          return `${row.allocationName}(${row.isNeedChild == 1 ? '包含下属部门' : '不包含下属部门'})`
        }
      }
      if (column.property == 'ratio') {
        return row.rate
      }
      if (column.property == 'money') {
        return this.formatMoney(row.royalty || 0)
      }
      return row[column.property] === '' || row[column.property] === null
        ? '--'
        : row[column.property]
    },

    /**
     * @description: 格式化字段
     * @param {*} row
     * @param {*} column
     * @return {*}
     */
    createFieldFormatter(row, column) {
      if (column.property == 'allocation') {
        if (row.allocationType == 0) { // 员工
          return row.allocationName
        } else if (row.allocationType == 1) { // 部门
          return `${row.allocationName}(${row.isNeedChild == 1 ? '包含下属部门' : '不包含下属部门'})`
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../styles/relativecrm.scss";
@import "../styles/table.scss";

.relative-amount-ratio {
  min-height: 400px;

  .empty {
    height: 450px;

    ::v-deep .empty-content {
      top: auto;
    }
  }
}

.amount-ratio-table-item {
  & + & {
    margin-top: 20px;
  }

  .amount-ratio-table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.amount-ratio-dialog {
  .el-dialog__body {
    padding-top: 0;

    & > .el-button {
      display: block;
      margin-bottom: 10px;
      margin-left: auto;
    }
  }
}
</style>
